import subprocess
import numpy as np
import pickle
import os, sys


def saveobject(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)



def read(channel=0, nrsamples=1):
    cmdstr = "sudo /usr/local/bin/natinst/rpi/aiondemand -c " + str(channel) + " -s " + str(nrsamples) + " -t 1000 -v"
    proc = subprocess.Popen(cmdstr, shell=True, stderr=subprocess.PIPE,
                            stdout=subprocess.PIPE)
    return_code = proc.wait()
    data = np.array([])
    for line in proc.stdout:
        strg = line.rstrip()
        strg = strg.rstrip(',')
        try:
                nr = float(strg)
                data = np.append(data, [nr])
        except:
            pass
    return data


if __name__ == '__main__':
    data = read(channel=0, nrsamples=sys.argv[1])
    saveobject(data,'resultlog.pk')